import 'dart:async';
import 'package:flutter/material.dart';
import 'countdown_model.dart';

class CountdownWidget extends StatefulWidget {
  final CountdownModel countdownModel;

  CountdownWidget({@required this.countdownModel});

  @override
  State<StatefulWidget> createState() {
    return CountdownWidgetState();
  }
}

class CountdownWidgetState extends State<CountdownWidget> {
  Timer timer;

  @override
  void initState() {
    timer = Timer.periodic(Duration(seconds: 1), (_) {
      if (widget.countdownModel.isStop) {
        timer.cancel();
      } else {
        setState(() {
          widget.countdownModel.seconds--;

          if (widget.countdownModel.seconds <= 0) {
            timer.cancel();
            widget.countdownModel.submitPaper();
          }
        });
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    timer.cancel();
    timer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var seconds = widget.countdownModel.seconds;
    int h = seconds ~/ 3600;
    int m = seconds ~/ 60 - h * 60;
    int s = seconds - m * 60 - h * 3600;
    var mm = m >= 10 ? m.toString() : '0$m';
    var ss = s >= 10 ? s.toString() : '0$s';

    return Padding(
      padding: EdgeInsets.only(top: 3),
      child: Text(
        seconds > 0 ? mm + ':' + ss : seconds.toString(),
        style: TextStyle(
          color: Color.fromRGBO(136, 136, 136, 1),
          fontSize: 14,
        ),
      ),
    );
  }
}
